package com.kmproject.haifu.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.hfinterface.PopuWindowSearchHistoryInterface;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.PopuwindowContralUtils;
import com.kmproject.haifu.di.component.DaggerSecondHandMainShowComponent;
import com.kmproject.haifu.mvp.contract.SecondHandMainShowContract;
import com.kmproject.haifu.mvp.model.entity.beans.SecondHandCategoryBean;
import com.kmproject.haifu.mvp.model.entity.beans.SecondHandInfoBean;
import com.kmproject.haifu.mvp.model.entity.resbean.PopuWindowSelectSearchBean;
import com.kmproject.haifu.mvp.model.entity.resbean.SecondHandQueryParmar;
import com.kmproject.haifu.mvp.presenter.SecondHandMainShowPresenter;
import com.kmproject.haifu.mvp.ui.adapter.SecondHandCategoryAdapter;
import com.kmproject.haifu.mvp.ui.adapter.SecondHandMainShowAdapter;
import com.kmproject.haifu.mvp.ui.widget.ScaleTransitionPagerTitleView;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.OnRefreshLoadMoreListener2;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.PullToRefreshView;
import com.library.flowlayout.SpaceItemDecoration;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.xw.repo.XEditText;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 08/29/2019 19:26
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class SecondHandMainShowActivity extends BaseActivity<SecondHandMainShowPresenter> implements SecondHandMainShowContract.View {

    @BindView(R.id.include_title_search_back)
    ImageView includeTitleSearchBack;
    @BindView(R.id.include_title_search_xedit)
    XEditText includeTitleSearchXedit;
    @BindView(R.id.popuwindow_selectsearchaddress_searchRootlay)
    LinearLayout popuwindowSelectsearchaddressSearchRootlay;
    @BindView(R.id.include_title_search_msg)
    ImageView includeTitleSearchMsg;
    @BindView(R.id.include_title_search_lay)
    LinearLayout includeTitleSearchLay;
    @BindView(R.id.ll_top_search_layout)
    LinearLayout llTopSearchLayout;
    @BindView(R.id.secondhand_show_RecyclerView)
    RecyclerView secondhandShowRecyclerView;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R.id.secondhand_show_indicator)
    MagicIndicator secondhandShowIndicator;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.secondhand_show_RecyclerView_content)
    RecyclerView secondhandShowRecyclerViewContent;

    SecondHandMainShowAdapter secondHandMainShowAdapter;
    SecondHandQueryParmar secondHandQueryParmar = new SecondHandQueryParmar();
    List<String> titles = new ArrayList<>();
    SecondHandCategoryAdapter secondHandCategoryAdapter;
    @BindView(R.id.secondhand_show_PullToRefreshView)
    PullToRefreshView secondhandShowPullToRefreshView;
     int curryPage=1;
     int selectIndex=0;
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerSecondHandMainShowComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_second_hand_main_show; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        includeTitleSearchXedit.setEnabled(false);
        includeTitleSearchXedit.setHint("搜索商品");
        secondHandCategoryAdapter = new SecondHandCategoryAdapter(new ArrayList<>());
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        secondhandShowRecyclerView.setLayoutManager(layoutManager);
        secondhandShowRecyclerView.addItemDecoration(new SpaceItemDecoration(AppUtil.dp2px(10)));
        secondhandShowRecyclerView.setAdapter(secondHandCategoryAdapter);
        secondHandCategoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                  Intent intent=new Intent(SecondHandMainShowActivity.this,SecondHandListShowActivity.class);
                  intent.putExtra("SecondHandCategoryBean",(SecondHandCategoryBean)secondHandCategoryAdapter.getData().get(position));
                  ArmsUtils.startActivity(intent);
            }
        });
        secondhandShowRecyclerViewContent.setLayoutManager(new GridLayoutManager(this, 2));
        secondhandShowRecyclerViewContent.addItemDecoration(new SpaceItemDecoration(AppUtil.dp2px(10)));
        secondHandMainShowAdapter = new SecondHandMainShowAdapter(new ArrayList<>());
        secondhandShowRecyclerViewContent.setAdapter(secondHandMainShowAdapter);
        secondHandMainShowAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        titles = Arrays.asList(getResources().getStringArray(R.array.secondhand_show_main_tab));
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return titles.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {

                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
                simplePagerTitleView.setText(titles.get(index));
                DisplayMetrics dm = getResources().getDisplayMetrics();
//                simplePagerTitleView.setWidth((dm.widthPixels) / 2);
                simplePagerTitleView.setTextSize(16);
                simplePagerTitleView.setNormalColor(getResources().getColor(R.color.color_191919));
                simplePagerTitleView.setSelectedColor(getResources().getColor(R.color.color_191919));
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//                layoutParams.setMargins(15, 0, 5, 0);//4个参数按顺序分别是左上右下
                simplePagerTitleView.setLayoutParams(layoutParams);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        secondhandShowIndicator.onPageSelected(index);
                        commonNavigator.getAdapter().notifyDataSetChanged();
                        if (index == 2) {
                            if (!AppUtil.userIsLogin(SecondHandMainShowActivity.this)) {
                                ArmsUtils.startActivity(UserLoginActivity.class);
                                secondhandShowRecyclerViewContent.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        showMessage("请先登录");
                                    }
                                });

                                return;
                            }
                            //请求关注的信息
                        }
                        selectIndex=index;
                        showIndexControl(true,index);
                    }
                });

                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setLineHeight(8.0f);
                linePagerIndicator.setColors(ArmsUtils.getColor(SecondHandMainShowActivity.this, R.color.color_F9D35A));
                return linePagerIndicator;
            }

            @Override
            public float getTitleWeight(Context context, int index) {
                return 1.0f;
            }

        });
        includeTitleSearchBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                killMyself();
            }
        });
        mPresenter.listSecondCategory("", "", "");
        secondhandShowIndicator.setNavigator(commonNavigator);
        showIndexControl(true,selectIndex);
        secondhandShowPullToRefreshView.setEnableRefresh(false);
        secondhandShowPullToRefreshView.setEnableAutoLoadMore(false);
        secondhandShowPullToRefreshView.setEnableHeaderTranslationContent(true);
        secondhandShowPullToRefreshView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                curryPage++;
                showIndexControl(false,selectIndex);
            }
        });
        popuwindowSelectsearchaddressSearchRootlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopuwindowContralUtils.getPopuwindowContralUtils().showPopuWindowToSearch(SecondHandMainShowActivity.this, includeTitleSearchXedit, new PopuWindowSearchHistoryInterface() {
                    @Override
                    public void callBack(String content, PopuWindowSelectSearchBean popuWindowSelectSearchBean) {
                        //跳转到搜索界面
                    Intent intent =new Intent(SecondHandMainShowActivity.this, SecondHandListShowActivity.class);
                    intent.putExtra("searchContent",popuWindowSelectSearchBean!=null?popuWindowSelectSearchBean.getContent():content);
                    ArmsUtils.startActivity(intent);
                    }
                });
            }
        });
    }

    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    public void showIndexControl(boolean isRefersh,int index) {
        List<SecondHandQueryParmar.SortOrdersBean> sortOrdersBeans = new ArrayList<>();
        if (isRefersh)
        {
            secondHandMainShowAdapter.setNewData(null);
        }

        switch (index) {
            case 0:
                //最新
                if (secondHandQueryParmar.getSortOrders() != null) {
                    secondHandQueryParmar.getSortOrders().clear();
                }
                sortOrdersBeans.add(new SecondHandQueryParmar.SortOrdersBean("desc", "viewCount"));
                secondHandQueryParmar.setSortOrders(sortOrdersBeans);
                secondHandQueryParmar.setPage(curryPage);
                mPresenter.listSecondHand(secondHandQueryParmar);
                break;
            case 1:

                if (secondHandQueryParmar.getSortOrders() != null) {
                    secondHandQueryParmar.getSortOrders().clear();
                }
                sortOrdersBeans.add(new SecondHandQueryParmar.SortOrdersBean("desc", "createTime"));
                secondHandQueryParmar.setSortOrders(sortOrdersBeans);
                secondHandQueryParmar.setPage(curryPage);
                mPresenter.listSecondHand(secondHandQueryParmar);
                break;
            case 2:
                // 关注   { name: "关注", dictId: "3", keys: "/myAttention" }
                if (secondHandQueryParmar.getSortOrders()!=null)
                {
                    secondHandQueryParmar.getSortOrders().clear();
                }
                secondHandQueryParmar.setSortOrders(null);
                secondHandQueryParmar.setPage(curryPage);
                mPresenter.myAttention(secondHandQueryParmar);
                break;


        }
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void listSecondHandSuccessa(int mcurryPage,List<SecondHandInfoBean> secondHandInfoBeans) {
        secondhandShowPullToRefreshView.finishLoadMore();
        if (secondHandInfoBeans==null||secondHandInfoBeans.isEmpty())
        {
            secondhandShowPullToRefreshView.setEnableLoadMore(false);
            if (secondHandMainShowAdapter.getData()==null||secondHandMainShowAdapter.getData().isEmpty())
            {
               //设置空
                secondHandMainShowAdapter.setEmptyView(AppUtil.setEmptyView(this,"没有二手物品信息","",null,true));
            }
            return;
        }
        if (secondHandMainShowAdapter.getData()==null||secondHandMainShowAdapter.getData().isEmpty())
        {
            secondHandMainShowAdapter.setNewData(secondHandInfoBeans);
        }else {
            secondHandMainShowAdapter.addData(secondHandInfoBeans);
        }
        curryPage=mcurryPage;
        if (secondHandInfoBeans.size()< AppConstant.pageSize)
        {
            secondhandShowPullToRefreshView.setEnableLoadMore(false);
        }else {
            secondhandShowPullToRefreshView.setEnableLoadMore(true);
        }

    }

    @Override
    public void listSecondCategorySuccess(List<SecondHandCategoryBean> secondHandCategoryBeans) {
        secondHandCategoryAdapter.setNewData(secondHandCategoryBeans);
    }
}
